package cn.liyicun.test.service;

import cn.hutool.core.bean.BeanUtil;
import cn.liyicun.test.bean.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    JdbcTemplate jdbc;

    public long addUser(String user, String passwd, String fullName, String ip) {
        PreparedStatementCreator psc = con -> {
            String sql = "INSERT INTO `user_info` (`username`, `passwd`, `create_time`, `balance`, `update_time`, `login_time`, `full_name`,status,reg_ip) VALUES (?,?,now(),?,now(),now(),?,1,?)";
            PreparedStatement ps = con.prepareStatement(sql, new String[]{"id"});
            ps.setString(1, user);
            ps.setString(2, passwd);
            ps.setBigDecimal(3, BigDecimal.valueOf(100));
            ps.setString(4, fullName);
            ps.setString(5, ip);
            return ps;
        };

        KeyHolder holder = new GeneratedKeyHolder();
        jdbc.update(psc, holder);
        //return jdbc.update(sql,user,passwd,new Date(),0,new Date(),new Date(),fullName);
        return holder.getKey().longValue();
    }

    public Long existUserName(String userName) {
        String sql = "select count(*) from user_info where username=?";
        return jdbc.queryForObject(sql, new String[]{userName}, Long.class);
    }

    public UserInfo queryByUserName(String userName) {
        String sql = "select * from user_info where username=? limit 1";

        List<Map<String, Object>> list = jdbc.queryForList(sql, new String[]{userName});
        if (list.isEmpty()) return null;
        return BeanUtil.mapToBean(list.get(0), UserInfo.class, false);

    }


    public List<Map<String, Object>> activeUser( ) {
        String sql = "SELECT * FROM `user_info` where status=1  ORDER BY `login_time` DESC LIMIT 0, 400";

        return jdbc.queryForList(sql );


    }



    public Long countUser() {
        String sql = "select count(*) from user_info";
        return jdbc.queryForObject(sql, Long.class);
    }

    public int updateLoginLog(Long uid, String ip) {

        jdbc.update("INSERT INTO `user_login_ip_log` (`uid`, `ip`, `create_time`) VALUES (?,?,now())", uid, ip);

        String sql = "UPDATE `user_info` SET `login_time`=now(), `login_ip`=? WHERE (`id`=?)";
        return jdbc.update(sql, ip, uid);
    }


}
